<!-- Markdown编辑器 -->
<template>
  <div class="markdown-container">
    <!-- 渲染区 -->
    <div id="markdown-box"></div>
    <!-- 底部按钮 -->
    <div class="bottom">
      <el-button type="primary" @click="onSubmitClick">{{ $t('msg.article.commit') }}</el-button>
    </div>
  </div>
</template>

<script setup>
import { onMounted, defineProps, defineEmits, watch } from 'vue'
import MKeditor from '@toast-ui/editor'
import '@toast-ui/editor/dist/toastui-editor.css'
import '@toast-ui/editor/dist/i18n/zh-cn'
import { useStore } from 'vuex'
import { watchSwitchLang } from '@/utils/i18n'
import { commitArticle, editArticle } from './commit'

const pops = defineProps({
  title: {
    required: true,
    type: String
  },
  detail: {
    type: Object
  }
})

const emits = defineEmits(['onSuccess'])

// Editor 实例
let mKeditor
let el

onMounted(() => {
  el = document.querySelector('#markdown-box')
  initEditor()
})

const store = useStore()
const initEditor = () => {
  mKeditor = new MKeditor({
    // el 渲染的区域
    el,
    // 高度
    height: '600px',
    // 样式
    previewStyle: 'vertical',
    // 国际化
    language: store.getters.language === 'zh' ? 'zh-CN' : 'en'
  })
  mKeditor.getMarkdown()
}

// 处理提交
const onSubmitClick = async () => {
  if (pops.detail && pops.detail._id) {
    // 编辑文章
    await editArticle({
      id: pops.detail._id,
      title: pops.title,
      content: mKeditor.getHTML()
    })
  } else {
    // 创建文章
    await commitArticle({
      title: pops.title,
      content: mKeditor.getHTML()
    })
  }

  mKeditor.reset()
  emits('onSuccess')
}

watchSwitchLang(() => {
  if (!el) return
  const htmlStr = mKeditor.getHTML()
  mKeditor.destroy()
  initEditor()
  mKeditor.setHTML(htmlStr)
})

// 编辑相关
watch(
  () => pops.detail,
  (val) => {
    if (val && val.content) {
      mKeditor.setHTML(val.content)
    }
  },
  {
    immediate: true
  }
)
</script>
<style lang="scss" scoped>
.markdown-container {
  .bottom {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
